import type { ElTree } from 'element-plus'
import { onBeforeMount, reactive, type Ref, toRefs, watch } from 'vue'

import { deptApi, type ITreeNode } from '@/apis'
import type { GridExtHook } from '@/hooks'

type Params = {
  gridExtHook: GridExtHook
  selectedKey: Ref<string>
}

type TreeRef = InstanceType<typeof ElTree>

export function useDept({ gridExtHook, selectedKey }: Params) {
  const state = reactive({
    deptTreeRef: {} as TreeRef,
    deptTreeData: [] as ITreeNode[],
    treeLoading: false,
    searchValue: ''
  })

  /**
   * 获取部门树
   */
  async function getDeptTree() {
    state.treeLoading = true

    state.deptTreeData = await deptApi.getDeptTree()

    state.treeLoading = false
  }

  /**
   * 选择部门
   */
  function handleSelectDept(value: ITreeNode) {
    selectedKey.value = value.key
    gridExtHook.refresh()
  }

  /**
   * 过滤部门
   */
  function handleFilterDept(value: string, data: ITreeNode) {
    if (!value) return true
    return data.title?.includes(value)
  }

  watch(
    () => state.searchValue,
    val => {
      state.deptTreeRef.filter(val)
    }
  )

  onBeforeMount(() => {
    getDeptTree()
  })

  return {
    ...toRefs(state),
    handleSelectDept,
    handleFilterDept
  }
}
